package com.tangji.signaltower.runners;

import com.alibaba.fastjson.JSON;
import com.tangji.antenna.bean.EventFactory;
import com.tangji.antenna.bean.ProviderTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.io.IOException;
import java.lang.InterruptedException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.websocket.*;

@ClientEndpoint
public class WSClient {
    private static Logger logger = LoggerFactory.getLogger(WSClient.class);
    public static List<String> actives = new ArrayList<>();

    public Session session;
    public static int msgNum = 0;
    public static int tt = 0;


    @OnOpen
    public void onOpen(Session session) throws java.io.IOException {
        List<String> ticks = new ArrayList<>();
        ticks.add("frxGBPUSD");
        ticks.add("frxEURUSD");
        Map<String, Object> request = new HashMap<>();
        request.put("ticks", ticks);
        request.put("subscribe", 1);

        String ticksStr = JSON.toJSONString(request);
        this.session = session;
        session.getBasicRemote().sendText(ticksStr);
    }

    /**
     * ask price  要价 就是卖价
     * bid price 就是买入价
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        logger.info("== 收到数据源的消息 ==,message:{}", message);
        msgNum++;
        if (msgNum > 2000) {
            msgNum = 0;
        }

        EventFactory.saveDataToQueue(ProviderTypeEnum.POLYGON, message, null);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        try {
            session.close();
        } catch (IOException e) {
            logger.error("Session  closed because of ,reason:{}", closeReason);
        }
    }

    /**
     * To execute when an error occurs
     *
     * @param t
     */
    @OnError
    public void onError(Throwable t) {
        logger.error("Session  onError,msg:{}", t.getMessage());
    }

}
